package com.doradance.app.appactivity.search;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.doradance.R;
import com.doradance.account.utils.FragmentUtils;
import com.doradance.account.utils.ListDataSave;
import com.doradance.app.MainActivity;
import com.doradance.entity.ShowSearchEntity;
import com.doradance.entity.clearListEntity;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.yuyh.library.BubblePopupWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.OnClick;

public class SearchActivity extends BaseActivity {

    @Bind(R.id.tv_search_type)
    TextView mTvSearchType;
    public String search_type = "课程";
    @Bind(R.id.et_search_history)
    EditText mEtSearchHistory;
    ListDataSave dataList;
    ListDataSave babyDataList;
    ArrayList<String> mArrayList = new ArrayList();
    ArrayList<String> mBabyArrayList = new ArrayList();

    @Bind(R.id.iv_delete_search)
    ImageView mIvDeleteSearch;

    private boolean isBaby = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mEtSearchHistory.setFocusable(true);

        dataList = new ListDataSave(this, "searchhistory");
        Log.e("dfds",dataList.getDataList("searchhistory").size()+"");
        for (int i = 0; i < dataList.getDataList("searchhistory").size(); i++) {
            mArrayList.add(dataList.getDataList("searchhistory").get(i).toString());
        }
        babyDataList = new ListDataSave(this, "searchbabayhistory");
        Log.e("dfdsbaby",babyDataList.getDataList("searchbabayhistory").size()+"");
        for (int i = 0; i < babyDataList.getDataList("searchbabayhistory").size(); i++) {
            mBabyArrayList.add(babyDataList.getDataList("searchbabayhistory").get(i).toString());
        }
        hideToolbar();
        //监听键盘的确定键
        watchSearch();
        FragmentUtils.addFirstFragment(getSupportFragmentManager(), R.id.fl_search, new SearchHomeFragment());
    }

    private void watchSearch() {
        mEtSearchHistory.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    // 先隐藏键盘
                    ((InputMethodManager) mEtSearchHistory.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(SearchActivity.this
                                            .getCurrentFocus().getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    if (TextUtils.isEmpty(mEtSearchHistory.getText().toString())) {
                        EasyToast.showToast(getApplicationContext(), "请输入你感兴趣的内容");
                    } else if (isBaby == false) {
                        mArrayList.add(mEtSearchHistory.getText().toString());
                        dataList.setDataList("searchhistory", mArrayList);
                        SearchVideoFragment searchVideoFragment = new SearchVideoFragment(mEtSearchHistory.getText().toString());
                        FragmentUtils.replaceFragment(getSupportFragmentManager(), R.id.fl_search, searchVideoFragment);
                        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

                    } else if (isBaby == true) {
                        mBabyArrayList.add(mEtSearchHistory.getText().toString());
                        babyDataList.setDataList("searchbabayhistory", mBabyArrayList);
                        SearchBabyFragment searchBabyFragment = new SearchBabyFragment(mEtSearchHistory.getText().toString());
                        FragmentUtils.replaceFragment(getSupportFragmentManager(), R.id.fl_search, searchBabyFragment);
                        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                    return true;
                }
                return false;
            }
        });
        mEtSearchHistory.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                mIvDeleteSearch.setVisibility(View.VISIBLE);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(clearListEntity refreshEvent) {
        if(refreshEvent.isBaby=false){
            mArrayList.clear();
            dataList.clearDataList();
        }else{
            mBabyArrayList.clear();
            babyDataList.clearDataList();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ShowSearchEntity refreshEvent) {
        mEtSearchHistory.setText(refreshEvent.text);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_search1, null);
    }

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, SearchActivity.class);
        activity.startActivity(intent);
    }

    @OnClick({R.id.rl_search_type, R.id.tv_search_cancel,R.id.iv_delete_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_search_type:
                final BubblePopupWindow buttomWindow = new BubblePopupWindow(SearchActivity.this);
                View bubbleView = getLayoutInflater().inflate(R.layout.layout_popup_view, null);
                TextView tvContent = (TextView) bubbleView.findViewById(R.id.tvContent);
                if (mTvSearchType.getText().toString().equals("课程")) {
                    tvContent.setText("宝宝");
                } else {
                    tvContent.setText("课程");

                }
                buttomWindow.setBubbleView(bubbleView); // 设置气泡内容
                buttomWindow.show(view, Gravity.BOTTOM, 0); // 显示弹窗
                bubbleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mTvSearchType.getText().toString().equals("课程")) {
                            mTvSearchType.setText("宝宝");
                            search_type = "宝宝";
                            FragmentUtils.replaceFragment(getSupportFragmentManager(), R.id.fl_search, new SearchHomeBabyFragment());
                            isBaby = true;
                        } else {
                            mTvSearchType.setText("课程");
                            search_type = "课程";
                            FragmentUtils.replaceFragment(getSupportFragmentManager(), R.id.fl_search, new SearchHomeFragment());
                            isBaby = false;
                        }
                        buttomWindow.dismiss();
                    }
                });
                break;
            case R.id.tv_search_cancel:
                finish();
                break;
            case R.id.iv_delete_search:
                mEtSearchHistory.setText("");
                mIvDeleteSearch.setVisibility(View.GONE);

                if(isBaby==true){
                    FragmentUtils.replaceFragment(getSupportFragmentManager(), R.id.fl_search, new SearchHomeBabyFragment());
                }else{
                    FragmentUtils.replaceFragment(getSupportFragmentManager(), R.id.fl_search, new SearchHomeFragment());
                }

                break;
        }
    }
}
